package com.moli.iov.admin.websocket.base;

import com.moli.iov.admin.websocket.handle.WebSocketBizHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;

/**
 * 发送消息
 */
@Slf4j
@Component
public class TextMessageHandler extends TextWebSocketHandler {

    @Resource
    WebSocketBizHandler webSocketHandler;

    /**
     * 链接成功后
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //设置数据传输限制
        session.setTextMessageSizeLimit(session.getTextMessageSizeLimit() * 5000);
        log.info("[websocket][afterConnectionEstablished][sessionId:{}][ connect success ...]", session.getId());
    }

    /**
     * 处理消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
    }

    /**
     * 处理消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        webSocketHandler.handle(message.getPayload(),session);
        super.handleTextMessage(session, message);
    }

    /**
     * 处理传输异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        log.error("处理传输异常 ", exception);
        log.info("websocket transport error and connection closed......");
        webSocketHandler.remove(session.getId());
    }

    /**
     * 关闭连接
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("websocket connection closed......");
        webSocketHandler.remove(session.getId());
    }

}
